<template>
  <div class="course">
    <Navbar></Navbar>
    <!-- 搜索框 -->
    <van-search
      v-model="value"
      placeholder="请输入搜索关键词"
      @search="onSearch()"
      @clear="onClear"
    />

    <!-- 课程列表 -->
    <van-grid :border="false" :column-num="2">
      <van-grid-item v-for="item in courseList" :key="item.id">
        <van-image :src="'http://localhost:3000' + item.imgurl" />
        <h4>{{ item.name }}</h4>
        <p>{{ item.desc }}</p>
      </van-grid-item>
    </van-grid>

    <Tabbar />
  </div>
</template>

<script setup>
import Navbar from "@/components/Navbar.vue";
import Tabbar from "@/components/Tabbar.vue";
import axios from "axios";
import { ref, onMounted } from "vue";

const courseList = ref([]);
const value = ref("");

function onClear() {
    getCourseList();
}
function onSearch() {
  // 根据搜索框内容过滤
  if (value.value === "") {
    getCourseList();
  } else {
    courseList.value = courseList.value.filter((item) =>
      item.name.includes(value.value)
    );
  }
}
function getCourseList() {
  axios
    .get("http://localhost:3000/courses")
    .then((result) => {
      //   console.log(result.data);
      courseList.value = result.data;
    })
    .catch((err) => {
      console.log(err);
    });
}
onMounted(() => {
  getCourseList();
});
</script>

<style scoped>
</style>